/**
 * Copyright 2008 Vidar Svansson
 *
 * This file is part of JAdapter.
 *
 * JAdapter is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JAdapter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JAdapter.  If not, see <http://www.gnu.org/licenses/>.
 */


package org.jadapter.spring;

import org.jadapter.adapters.AutoConfigAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.lang.reflect.Type;

/**
 *
 * @author Vidar Svansson
 * @since 0.3
 */
public class SpringAdapter<T, F> extends AutoConfigAdapter<T, F> implements BeanFactoryAware {

    private BeanFactory factory;

    private final String beanName;

    private String transformer;

    private Method method;

    public SpringAdapter(Class<?> factory, String beanName) {
        super(factory);
        this.beanName = beanName;
    }

    public SpringAdapter(Class<?> factory, String beanName, String transformer) {
        super(factory);
        this.beanName = beanName;
        this.transformer = transformer;
    }

    private Method findMethod(Object bean) {
        if (method == null) {

            // TODO propertly find the correct method
            method = ReflectionUtils.findMethod(bean.getClass(),
                    transformer, null);

        }
        return method;
    }


    @Override
    public T doTransform(F context, Type type) {
        Object bean = factory.getBean(beanName);
        Method m = findMethod(bean);

        Object result = ReflectionUtils.invokeMethod(m, bean, new Object[]{context});
        return resultOrSelf(type, result, bean);
    }

    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.factory = beanFactory;
    }


    public void setTransformer(String transformer) {
        this.transformer = transformer;
    }

    public void setFrom(Class<?> from){
        from(from);
    }

    public void setTo(Class<?> to){
        to(to);
    }    
}
